<?php


namespace app\api\controller;

use app\api\model\Goods;
use think\Db;
use think\Exception;
use app\api\model\Rush as rushModel;

//https://cosimo.qswh.net.cn/api/Rush/getRush
class Rush extends BaseApi {
    //购买商品
    public function rush(){
        if (!$this->request->param('openid')
            || !$this->request->param('goodsid')
            || !$this->request->param('price')) {
            return json(['code' => -1, 'msg' => '缺少参数']);
        }

        $openid = trim($this->request->param('openid'));
        $goodsid = intval($this->request->param('goodsid'));
        $price = trim($this->request->param('price'));

        $goods = new Goods();
        $goodsItem = $goods->getGoodsDetail($goodsid);
        if(empty($goodsItem)){
            return json(['code' => -1, 'msg' => '商品不存在或已删除']);
        }

        if($price < $goodsItem->pprice){
            $price = $goodsItem->pprice;
        }

        $rush = new \app\api\model\Rush();

        $rushsn = 'RS'.date('Ymd').$this->random(6);
        $rush->openid = $openid;
        $rush->goodsid = $goodsid;
        $rush->rushsn = $rushsn;
        $rush->price = $price;
        $rush->createtime = time();

        Db::startTrans();
        try{
            $rush->save();
            if(!$rush->id){
                return json(['code' => -1, 'msg' => '订单生成失败']);
            }
            //支付订单
            $payData = [
                'total_fee' => $price,
                'out_trade_no' => $rushsn,
                'openid' => $openid
            ];
            $payResult = $this->processPay('rush',$payData,'购买商品');
            if(empty($payResult)){
                return ['code'=>-1,'msg'=>'订单支付失败'];
            }
            Db::commit();
            return json(['code'=>1,'data'=>$payResult]);
        }catch (Exception $e){
            Db::rollback();
            return json(['code'=>-1,'msg'=>$e->getMessage()]);
        }
    }


    //全部订单
    public function getRushList(){
        if (!$this->request->param('openid') || !$this->request->param('page')){
            return json(['code' => -1, 'msg' => '缺少参数']);
        }

        $openid = trim($this->request->param('openid'));
        $page = max(1,intval($this->request->param('page')));
        $pagesize = intval($this->request->param('pagesize'));
        $rush  = new rushModel();
        $rushList = $rush->getRushList(['openid'=>$openid],$page,$pagesize);
        return json(['code'=>1,'data'=>$rushList]);
    }


    //获取订单详情
    public function getRush(){
        if (!$this->request->param('rushid')){
            return json(['code' => -1, 'msg' => '缺少参数']);
        }
        $rushid = intval($this->request->param('rushid'));
        $rush = new rushModel();
        $rushItem = $rush->getRush(['id'=>$rushid],['rushsn','goodsid','id','price']);
        if(empty($rushItem)){
            return json(['code'=>-1,'msg'=>'订单不存在或已删除']);
        }
        return json(['code'=>1,'data'=>$rushItem]);
    }
}